package com.fxd.dao.impl;

import com.fxd.dao.IAccountDao;
import com.fxd.domain.Account;
import com.fxd.uitls.connectionUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {


    private QueryRunner runner;
    private connectionUtil conn;

    public void setConn(connectionUtil conn) {
        this.conn = conn;
    }

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public Account findAccountByName(String accountName) {
        try {
            List<Account> accounts = runner.query(conn.getThreadConnection(),"select * from account where name= ? ", new BeanListHandler<Account>(Account.class), accountName);
            if(accounts==null || accounts.size()==0){
                return null;
            }
            if (accounts.size()> 1){
                throw new RuntimeException("结果集不唯一");
            }
            return accounts.get(0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void updateAccount(Account account) {
        try{
            runner.update(conn.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
